package com.qianfeng.freeshiro.service;

import com.qianfeng.freeshiro.dao.AuthsMapper;
import com.qianfeng.freeshiro.dao.RolesMapper;
import com.qianfeng.freeshiro.dao.UsersMapper;
import com.qianfeng.freeshiro.entity.Users;
//import com.qianfeng.freeshiro.util.MyException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private RolesMapper rolesMapper;
    @Resource
    private AuthsMapper authsMapper;

    public void login(String username, String password){
        // 得到用户
        Subject user = SecurityUtils.getSubject();

        // 创建用户名和密码的验证方式的token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        // 登录
        try {
            user.login(token);
            System.out.println("登录成功");
        }catch (AuthenticationException e){
            e.printStackTrace();
            System.out.println("登录失败");
//            throw new MyException("E1001");
        }
    }

    public Users findByUsernameAndPwd(String userNumber, String pwd){
        return usersMapper.findByUserNumberAndPwd(userNumber, pwd);
    }

    public List<String> findRoleCodeByUserId(int userId){
        return rolesMapper.findRoleCodeByUserId(userId);
    }

    public List<String> findAuthsCodeByRoleCode(String roleCode){
        return authsMapper.findAuthsCodeByRoleCode(roleCode);
    }
}
